<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>
</head>
<style>
    .main-video {
        flex: 1;
        height: 300px;
    }
    video {
        width: 100%;
        height: 400px;
    }
    .video-title {
        margin: 10px;
        width: 40%;
        background-color: #000000b3;
        color: #fff;
        text-align: center;
        box-sizing: border-box;
        border: 1px solid #048ff2 ;
    }
    .video-container {
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        width: 100%;
        height: 100%;
    }
    .video-item{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 20px;
        width: 100%; 
        margin: 10px auto;
    }
    .button_link{
        margin-top: 40px;
        font-size: 1.5rem;
        background: #5bc1c9;
        height: 80px;
        color: white;
        /* width: 100px; */
        border-radius: 10px;
        border: none;
        width: 40%;
    }
</style>

<body>
    <div class="signaling-p2p-container">
        <div class="video-container">
            <div  class="video-item">  
                <video id="local" autoplay playsinline></video>
                <div class="video-title">我</div>
            </div>
            <div class="video-item">
                <video id="remote-video" class="remote-video" autoplay playsinline></video>
                <div class="video-title">远程视频</div>
            </div>
            
            <button class="button_link" onclick="initConnect()"> 点我开始连接</button>
        </div>
        <div class="operation">
            <!-- 房间号：
            <input v-model="roomId" style="width: 150px; margin-right: 20px" placeholder="要加入的房间号" clearable
                @keyup.enter="initConnect"></input>
            <button type="primary" @click="initConnect">加入</button>
            <button onclick="handleCamera()">点我</button>
            <button type="danger" @click="handleLeave">离开</button> -->
            <!-- <button :type="cameraOpen ? 'warning' : 'primary'" @click="handleMic">
            {{ cameraOpen ? '关闭' : '打开' }}麦克风
          </button> -->
            <!--   <button type="primary" @click="createAnswer(offerSdp)">
            创建answer
          </button>
          <button type="primary" @click="addAnswer">添加answer</button> -->
        </div>
    </div>
    <script>
        // 创造对象
        const peerConnection = new RTCPeerConnection({
            // iceServers: [
            //     {
            //         urls: 'stun:stun.voipbuster.com ',
            //     },
            // ],
        })
        const userId = Math.random().toString(36).substring(2)
        console.log(userId)

        // const roomId = ref('3333')
        let roomId = '332'
        let socket
        let localStream
        let remoteStream
        let offerSdp = ''

        // 第一步：初始化连接
        // 定义监听事件
        window.addEventListener('error',(e)=>{
            
        })
        function initConnect() {
            
            if (!roomId) {
                // ElMessage.error('请输入房间号')
                alert("请输入房间号")
                return
            }
            // socket = io('https://47.95.239.198:3000')
            try{socket = io('https://172.18.91.192:3000')}catch{
alert("出错")
            }
            
            // socket = io('https://signaling.fedtop.com')
            // 连接成功时触发
            socket.on('connect', () => {
                handleConnect()
            })
            // 断开连接时触发
            socket.on('disconnect', (reason) => {
                if (reason === 'io server disconnect') {
                    // 断线是由服务器发起的，重新连接。
                    socket.connect()
                }
                console.log("你已断开连接")
                // ElMessage.warning('您已断开连接')
            })
            // 服务端发送报错信息
            socket.on('error', (data) => {
                console.log("error", data)
                alert(e)
            })
            // 当有用户加入房间时触发
            socket.on('welcome', (data) => {
                console.log("welcome", data)
                
                console.log(`🦄${data.userId}加入房间`)
                // alert(`🦄${data.userId}加入房间`)
                // ElMessage.success(data.userId === userId ? '🦄成功加入房间' : )
            })
            // 当有用户离开房间时触发
            socket.on('leave', (data) => {
               
                console.log(`🦄${data.userId}离开房间`)
                // ElMessage.warning(data.userId === userId ? '🦄成功离开房间' : `🦄${data.userId}离开房间`)
            })
            // 当有用户发送消息时触发
            socket.on('message', (data) => { })
            // 创建offer,发送给远端
            socket.on('createOffer', (data) => {
                // 发送 offer
                if (offerSdp) {
                    socket.emit('createAnswer', {
                        userId,
                        roomId: roomId,
                        sdp: offerSdp,
                    })
                    return
                }
                createOffer()
            })
            // 收到offer,创建answer
            socket.on('createAnswer', (data) => {
                createAnswer(data.sdp)
            })
            // 收到answer,设置远端sdp
            socket.on('answer', (data) => {
                addAnswer(data.sdp)
            })
        }


        // initConnect()
        

        // 连接成功 发送xx加入了
        function handleConnect() {
            // 重要全局
            socket.emit('join', { userId, roomId: roomId })
        }
        const init = async () => {
            const localVideo = document.getElementById('local')
            const remoteVideo = document.getElementById('remote-video')
            localStream = await navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false,
            })
            remoteStream = new MediaStream()
            localVideo.srcObject = localStream
            remoteVideo.srcObject = remoteStream
            localStream.getTracks().forEach((track) => {
                peerConnection.addTrack(track, localStream)
            })
            peerConnection.ontrack = (event) => {
                event.streams[0].getTracks().forEach((track) => {
                    remoteStream.addTrack(track)
                })
            }
        }
        // 创建 offer
        async function createOffer() {
            // 当一个新的offer ICE候选人被创建时触发事件
            peerConnection.onicecandidate = async (event) => {
                if (event.candidate) {
                    offerSdp = JSON.stringify(peerConnection.localDescription)
                    // 发送 offer
                    if (offerSdp) {
                        socket.emit('createAnswer', {
                            userId,
                            roomId: roomId,
                            sdp: offerSdp,
                        })
                    }
                }
            }
            const offer = await peerConnection.createOffer()
            await peerConnection.setLocalDescription(offer)
        }
        // 创建 answer
        async function createAnswer(val) {
            const offer = JSON.parse(val)
            peerConnection.onicecandidate = async (event) => {
                // 当一个新的 answer ICE candidate 被创建时
                if (event.candidate) {
                    socket.emit('answer', {
                        userId,
                        roomId: roomId,
                        sdp: JSON.stringify(peerConnection.localDescription),
                    })
                }
            }
            await peerConnection.setRemoteDescription(offer)
            const answer = await peerConnection.createAnswer()
            await peerConnection.setLocalDescription(answer)
        }
        // 添加 answer
        async function addAnswer(answerSdp) {
            const answer = JSON.parse(answerSdp)
            if (!peerConnection.currentRemoteDescription) {
                peerConnection.setRemoteDescription(answer)
            }
        }
        // 摄像头 
        const cameraOpen = true
        function handleCamera() {
            //   cameraOpen.value = !cameraOpen.value
            localStream.getVideoTracks().forEach((track) => {
                track.enabled = true
            })
        }
        // // 开关麦克风
        // const isAudioOpen = ref(true)
        // function handleMic() {
        //   localStream.getAudioTracks().forEach((track) => {
        //     track.stop()
        //   })
        //   isAudioOpen.value = !isAudioOpen.value
        // }
        // 离开房间
        function handleLeave() {
            // 关闭对等连接
            peerConnection.close()
            // 发送离开的消息
            socket.emit('leave', { userId, roomId: roomId })
            // 关闭socket连接
            socket.disconnect()
        }
        init()
    </script>
</body>

</html>